<?php
/**
 * Login.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/05
 * Time: 21:11
 */
namespace app\admin\controller;

use app\common\VerifyCodeTrait;
use think\Controller;

class Login extends Controller
{
    use VerifyCodeTrait;

    public function index()
    {
        $this->assign('remember_user',json_decode(cookie('admin_auth_remember_user'),true));
        return $this->fetch('tpl/login');
    }

    /**
     * 登录
     * @return \think\response\Json
     * @throws \Exception
     */
    public function signIn(){
        if(!$this->request->isPost()){
            throw new \Exception('非法请求');
        }
        // 验证验证码
        $this->checkVerifyCodeBySession($this->request->post('verify_code',''));

        // 进行登录
        $user = (new \app\api\open\user\Login($this->request->post()))->signIn();
//        Hook::listen("auth_success",$user);
        // 存储至session
        session('admin_auth.user',$user);
        session('admin_auth.expire',time());

        // 是否记住密码？
        if($this->request->post('remember',0) == 1){
            cookie('admin_auth_remember_user',json_encode($this->request->post()),3600*24);
        }else{
            cookie('admin_auth_remember_user',null);
        }

        return json(['code'=>200,'data'=>$user]);
    }
    // 登出
    public function signOut(){
        session('admin_auth',null);
        $this->redirect(get_url('/admin/login/index'));
    }
}